#include "TMath.h"
#include "TList.h"
#include "TTree.h"
#include "TH1D.h"
#include "TCanvas.h"
#include "TGraph.h"
#include "TDirectory.h"
#include "TFile.h"

#include "XGLUtils.h"

TList *ll=new TList;
TTree * tree = 0x0;

const Double_t EPSILON = 1e-12;

void draw(const TString var, const Double_t xmin, const Double_t xmax, const Double_t meancut)
{
  TString tag(var);
  tag.ReplaceAll("/","");
  tag.ReplaceAll(".","");

  TCanvas *c1=new TCanvas(tag+"h");
  gPad->SetGrid();
  gPad->SetLogy();
  TH1D *h0 = new TH1D(Form("%s0", tag.Data()),"", 1000, xmin, xmax);
  TH1D *h1 = new TH1D(Form("%s1", tag.Data()),"", 1000, xmin, xmax);

  tree->Draw(Form("%s>>%s", var.Data(), h0->GetName()),Form("mean < %f && %s > 0", meancut, var.Data()));
  tree->Draw(Form("%s>>%s", var.Data(), h1->GetName()),Form("mean > %f && %s > 0", meancut, var.Data()));

  h0->Sumw2(); h0->Scale(1./h0->Integral(0,h0->GetNbinsX()));
  h1->Sumw2(); h1->Scale(1./h1->Integral(0,h1->GetNbinsX()));

  const Double_t hmax = TMath::Max(h0->GetBinContent(h0->GetMaximumBin()), h1->GetBinContent(h1->GetMaximumBin()));
  if(var.Contains("jp")){
    h0->SetMaximum(hmax*1.05);
  }
  else{
    h0->SetMaximum(1e-2);
    h0->SetMinimum(1e-6);
  }
  h0->SetLineColor(kRed);
  h0->Draw("hist");
  h1->Draw("same hist");
  c1->Print(tag+"h.png");

  TCanvas *c10=new TCanvas(tag+"hc");
  gPad->SetGrid();
  TH1D * hc0=XGLUtils::GetCDF(h0);
  TH1D * hc1=XGLUtils::GetCDF(h1);
  hc0->Draw("hist");
  hc1->Draw("same hist");
  c10->Print(tag+"cdf.png");

  TCanvas *c11=new TCanvas(tag+"contCanvas");
  gPad->SetGrid();
  TGraph *gr=new TGraph;
  gr->SetName(tag+"cont");
  Int_t np = 0;
  for(Int_t ii=1; ii<=hc0->GetNbinsX(); ii++){
    const Double_t eff = 1-hc1->GetBinContent(ii);
    const Double_t cont = 1-hc0->GetBinContent(ii);
    if(cont<EPSILON)
      continue;

    printf("%s %d %d: %15f %15f , %15f %15f\n", var.Data(), ii, np, hc0->GetBinCenter(ii), hc1->GetBinCenter(ii), eff, cont);
    gr->SetPoint(np, eff, 1./cont);
    np++;
  }
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(1);
  gr->SetMaximum(800);
  gr->GetXaxis()->SetLimits(0.8,1);
  gr->Draw("ap");
  c11->Print(tag+"rej.png");

  ll->Add(h0);
  ll->Add(h1);
  ll->Add(hc0);
  ll->Add(hc1);
  ll->Add(c1);
  ll->Add(c10);
  ll->Add(gr);
  ll->Add(c11);
}

int main(int argc, char * argv[])
{
  TFile::Open(argv[1]);

  tree=(TTree*)gDirectory->Get("tree");
  if(!tree){
    gDirectory->ls(); printf("no tree!!\n"); exit(1);
  }

  draw("trq/1.0235",  4, 7.5, 5.5);
  //  draw("mf",   4, 7.5, 5.5);
  draw("invl/0.9688", 4, 7.5, 5.5);
  draw("lgq/0.9967",  4, 7.5, 5.5);
  //  draw("inm",  4, 7.5, 5.5);
  draw("jp", -0.05, 1.05, 5.5);
  //draw("lr", -50, 5);

  TFile *fout=new TFile("hist.root","recreate");
  ll->Write();
  fout->Save();
  fout->Close();
}
